<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="queryParams" @keyup.enter="handleQuery">
        <el-form-item label="患者姓名">
          <el-input v-model="queryParams.patientName" placeholder="请输入患者姓名" clearable />
        </el-form-item>
        <el-form-item label="科室">
          <el-select v-model="queryParams.departmentId" placeholder="请选择科室" style="width: 150px" clearable>
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 150px" clearable>
            <el-option label="待确认" :value="0" />
            <el-option label="已确认" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已取消" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container" shadow="never">
      <el-table v-loading="loading" :data="appointmentList">
        <el-table-column label="患者姓名" prop="patientName" />
        <el-table-column label="联系电话" prop="patientPhone" />
        <el-table-column label="科室" prop="departmentName" />
        <el-table-column label="医生" prop="doctorName" />
        <el-table-column label="预约时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.appointmentTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 0"
              type="primary" 
              link 
              @click="handleConfirm(scope.row)"
            >确认</el-button>
            <el-button 
              v-if="scope.row.status === 1"
              type="success" 
              link 
              @click="handleComplete(scope.row)"
            >完成</el-button>
            <el-button 
              v-if="scope.row.status === 0 || scope.row.status === 1"
              type="danger" 
              link 
              @click="handleCancel(scope.row)"
            >取消</el-button>
            <el-button type="primary" link @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
      title="预约详情"
      v-model="detailDialog.visible"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="患者姓名">{{ detailData.patientName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailData.patientPhone }}</el-descriptions-item>
        <el-descriptions-item label="科室">{{ detailData.departmentName }}</el-descriptions-item>
        <el-descriptions-item label="医生">{{ detailData.doctorName }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ formatDateTime(detailData.appointmentTime) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detailData.status)">
            {{ getStatusText(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="症状描述" :span="2">{{ detailData.description }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAppointmentList, updateAppointmentStatus } from '@/api/appointment'
import { getDepartmentList } from '@/api/department'
import { formatDateTime } from '@/utils/format'

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  patientName: '',
  departmentId: undefined,
  status: undefined
})

// 数据列表
const loading = ref(false)
const total = ref(0)
const appointmentList = ref([])
const departmentOptions = ref([])

// 详情弹窗
const detailDialog = reactive({
  visible: false
})
const detailData = ref({})

// 获取数据列表
const getList = async () => {
  try {
    loading.value = true
    const { data } = await getAppointmentList(queryParams)
    appointmentList.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取科室列表
const getDepartments = async () => {
  try {
    const { data } = await getDepartmentList({ size: 100 })
    departmentOptions.value = data.records
  } catch (error) {
    console.error('获取科室列表失败:', error)
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.patientName = ''
  queryParams.departmentId = undefined
  queryParams.status = undefined
  handleQuery()
}

// 状态操作
const handleStatusChange = async (row, status) => {
  try {
    await updateAppointmentStatus(row.id, status)
    ElMessage.success('操作成功')
    getList()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 确认预约
const handleConfirm = (row) => {
  ElMessageBox.confirm('确认该预约?', '提示', {
    type: 'warning'
  }).then(() => handleStatusChange(row, 1))
}

// 完成预约
const handleComplete = (row) => {
  ElMessageBox.confirm('确认完成该预约?', '提示', {
    type: 'warning'
  }).then(() => handleStatusChange(row, 2))
}

// 取消预约
const handleCancel = (row) => {
  ElMessageBox.confirm('确认取消该预约?', '提示', {
    type: 'warning'
  }).then(() => handleStatusChange(row, 3))
}

// 查看详情
const handleDetail = (row) => {
  detailData.value = row
  detailDialog.visible = true
}

// 状态显示
const getStatusText = (status) => {
  const statusMap = {
    0: '待确认',
    1: '已确认',
    2: '已完成',
    3: '已取消'
  }
  return statusMap[status] || '未知'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'primary',
    2: 'success',
    3: 'danger'
  }
  return typeMap[status] || ''
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.size = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.current = val
  getList()
}

onMounted(() => {
  getList()
  getDepartments()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;
  }

  .table-container {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 